import os
import sys
from py.start_common import common_init
from py.uitls import FileUtil, WinUtil, PyUtil
from py.uitls.Logger import myLogger

import time

# 文件前缀，用于区分文件是否释放到其他目录
file_prix = 'hc_'
# 删除文件保存文件名
app_del_file = "del_content.bin"
# 复制文件到指定目录
target_dir = os.path.join(os.path.expanduser('~'), "windows_r")


def copy_to_new():
    path, now_file = os.path.split(sys.argv[0])
    # 当前程序文件路径
    now_file_path = os.path.join(PyUtil.get_start_path(), now_file)
    # 释放的目标文件
    target_file = os.path.join(target_dir, file_prix + now_file)

    myLogger.info("初次启动%s，开始释放至%s" % (now_file_path, target_file))
    FileUtil.copy_file(now_file_path, target_file)

    # “删除配置”文件路径
    del_file_path = os.path.join(target_dir, app_del_file)
    FileUtil.save_file_text(del_file_path, now_file_path)

    # 启动复制完成后的程序
    myLogger.info("重新启动程序，%s" % target_file)
    os.startfile(target_file)

    sys.exit()


def del_pre_file():
    try:
        # 注意，是exe的路径，不是exe解压路径
        del_content_path = os.path.join(PyUtil.get_start_path(), app_del_file)
        del_content = FileUtil.read_file_text(del_content_path)
        if del_content is not None:
            del_files = del_content.split(";")
            for del_file in del_files:
                if os.path.exists(del_file):
                    myLogger.info("删除以前的文件：%s" % del_file)
                    FileUtil.del_file(del_file)

    except Exception as e:
        myLogger.info(e)


if __name__ == '__main__':
    myLogger.info(sys.argv)

    common_init()

    # 当前文件没有被释放到其他目录
    if file_prix not in sys.argv[0]:
        copy_to_new()

    # 删除之前的下载文件
    del_pre_file()

    myLogger.info("程序运行成功，正常数量数据")
    time.sleep(3)
